package com.ctshk.rpc.order.scenic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.ApprovalStatus;
import com.ctshk.common.enums.SystemBusinessType;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.vo.OrderRefundDTO;
import com.ctshk.rpc.finance.req.bill.BillOperateRefundReq;
import com.ctshk.rpc.finance.service.IFinanceBillService;
import com.ctshk.rpc.order.scenic.dto.ScenicOrderRefundListDTO;
import com.ctshk.rpc.order.scenic.entity.ScenicOrder;
import com.ctshk.rpc.order.scenic.entity.ScenicOrderRefund;
import com.ctshk.rpc.order.scenic.mapper.ScenicOrderMapper;
import com.ctshk.rpc.order.scenic.mapper.ScenicOrderRefundMapper;
import com.ctshk.rpc.order.scenic.req.ScenicOrderRefundReq;
import com.ctshk.rpc.order.scenic.req.ScenicOrderRefundUpdateReq;
import com.ctshk.rpc.order.scenic.service.IScenicOrderRefundService;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.ISysUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 门票退款记录 服务实现类
 * </p>
 *
 * @author 张志朋
 * @since 2021-02-24
 */
@DubboService
public class ScenicOrderRefundServiceImpl extends ServiceImpl<ScenicOrderRefundMapper, ScenicOrderRefund> implements IScenicOrderRefundService {

    @Autowired
    private ScenicOrderRefundMapper scenicOrderRefundMapper;

    @DubboReference
    private ISysUserService iSysUserService;

    @DubboReference
    private IFinanceBillService iFinanceBillService;

    @Autowired
    private ScenicOrderMapper scenicOrderMapper;

    /**
     * 订单操作退款记录
     *
     * @param scenicOrderRefundReq
     * @return ScenicOrderRefundListDTO
     */
    @Override
    public Result<List<ScenicOrderRefundListDTO>> list(ScenicOrderRefundReq scenicOrderRefundReq) {
        QueryWrapper<ScenicOrderRefund> scenicOrderRefundQueryWrapper = new QueryWrapper<>();
        scenicOrderRefundQueryWrapper.eq("is_deleted", 0);
        scenicOrderRefundQueryWrapper.eq("order_id", scenicOrderRefundReq.getOrderId());
        List<ScenicOrderRefund> list = scenicOrderRefundMapper.selectList(scenicOrderRefundQueryWrapper);
        List<ScenicOrderRefundListDTO> scenicOrderRefundListDTOS = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (ScenicOrderRefund scenicOrderRefund : list) {
                ScenicOrderRefundListDTO scenicOrderTouristDTO = EntityUtil.copy(scenicOrderRefund, ScenicOrderRefundListDTO.class);
                //todo   上线去掉
                UserDTO userDTO = iSysUserService.loadUserByParam(scenicOrderRefund.getCreateId(), 1);
                scenicOrderTouristDTO.setCreateName(userDTO.getUsername());
                scenicOrderRefundListDTOS.add(scenicOrderTouristDTO);
            }
        }
        return Result.success(scenicOrderRefundListDTOS);
    }

    @Override
    @Transactional
    public Result<Long> refund(ScenicOrderRefundUpdateReq scenicOrderRefundUpdateReq, TokenUser tokenUser) {
        BillOperateRefundReq operateRefundReq = new BillOperateRefundReq();
        operateRefundReq.setUserId(tokenUser.getId());
        operateRefundReq.setBillNumber(scenicOrderRefundUpdateReq.getRefundNumber());
        operateRefundReq.setBusinessType(SystemBusinessType.ATTRACTION_TICKET.getCode());
        Result result = iFinanceBillService.operateRefund(operateRefundReq);
        if (result.isSuccess()) {
            Result<Long> longResult = operateRefund(scenicOrderRefundUpdateReq.getRefundNumber(), tokenUser.getId());
            if (longResult.isSuccess()) {
                return Result.success(longResult.getData());
            }else{
                throw new BusinessException(SystemError.SCENIC_5019,"财务调用成功后发生修改失败，异常。。。");
            }
        }else {
            return Result.failed(SystemError.SCENIC_5019,
                    "财务操作退款接口调用失败，给定的参数为：" +
                            operateRefundReq.getBillNumber() + "|" +
                            SystemBusinessType.ATTRACTION_TICKET.getCode() + "|" +
                            operateRefundReq.getUserId());
        }
    }

    @Override
    public Result<Long> operateRefund(String refundNumber, Long userId) {
        QueryWrapper<ScenicOrderRefund> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("refund_number", refundNumber);
        queryWrapper.eq("is_deleted", 0);
        ScenicOrderRefund scenicOrderRefund = scenicOrderRefundMapper.selectOne(queryWrapper);
        if (scenicOrderRefund != null) {
            scenicOrderRefund.setModifiedId(userId);
            scenicOrderRefund.setGmtModified(LocalDateTime.now());
            scenicOrderRefund.setStatus(ApprovalStatus.REFUND_SUCCESS.getCode());
            scenicOrderRefundMapper.updateById(scenicOrderRefund);
        }
        return Result.success(scenicOrderRefund.getId());
    }

    @Override
    public Result<List<OrderRefundDTO>> getRefundList(String orderNumber) {
        QueryWrapper<ScenicOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_number", orderNumber);
        queryWrapper.eq("is_deleted", 0);
        ScenicOrder scenicOrder = scenicOrderMapper.selectOne(queryWrapper);
        List<OrderRefundDTO> list = new ArrayList<>();
        List<ScenicOrderRefund>
                scenicOrderRefundList = scenicOrderRefundMapper.queryListByOrderNumber(orderNumber);
        for (ScenicOrderRefund sc : scenicOrderRefundList) {
            OrderRefundDTO orderRefundDTO = new OrderRefundDTO();
            orderRefundDTO.setRefundId(sc.getId());
            orderRefundDTO.setBusinessType(SystemBusinessType.ATTRACTION_TICKET.getCode());
            orderRefundDTO.setRefundNumber(sc.getRefundNumber());
            orderRefundDTO.setRefundReason(sc.getRefundReason());
            orderRefundDTO.setRemark(sc.getRemark());
            orderRefundDTO.setRefundType(sc.getRefundWay());
            orderRefundDTO.setTotalReceivables(scenicOrder.getReceivableAmount());
            orderRefundDTO.setPaidInAmount(scenicOrder.getOrderAmount());
            orderRefundDTO.setRefundAmount(sc.getRefundAmount());
            orderRefundDTO.setApprovalAmount(sc.getRefundAmount()); //审批退款金额
            orderRefundDTO.setCurrency(sc.getCurrency());
            orderRefundDTO.setRefundAccount(sc.getRefundAccount());
            list.add(orderRefundDTO);
        }
        return Result.success(list);
    }
}
